package com.fuyin.commons.handler;

import com.fuyin.commons.exception.ApiException;
import com.fuyin.commons.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yuanxilan (yuanxilan@keep.com)
 * @Description
 * @date 2021年10月27日 5:26 下午
 * @since
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     *
     * @param req
     * @param e
     * @return {@link BaseResponse}
     * @author 袁希岚
     * @date 2021/12/2 <br>
     * @since
     */
    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public BaseResponse apiExceptionHandler(HttpServletRequest req, ApiException e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMessage());
        return BaseResponse.error(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 处理空指针异常
     *
     * @param req
     * @param e
     * @return {@link BaseResponse}
     * @author 袁希岚
     * @date 2021/12/2 <br>
     * @since
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public BaseResponse exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！接口是: {}, 异常为: {}", req.getRequestURL().toString(), e);
        return BaseResponse.error(500, "空指针异常");
    }
}
